/*
   Copyright 2022 cmanlh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/**
 * text input
 * 
 */
import JscConfig from './config.js';
import JscDatabind from './databind.js';
import JscDialog from './dialog.js';
import JscButton from './button.js';

export default class JscInputTextarea extends JscDatabind {
    static get observedAttributes() { return ['required', 'closebymodal', 'readonly', 'disabled', 'placeholder', 'value', 'jscbind', 'maxlength'] }

    static editorBox = `
    <div class="inputTextareaEditorBox">
        <textarea class="inputTextareaEditor" placeholder="请输入" maxlength="256"></textarea>
        <div class="inputTextareaCounter"></div>
        <div class="inputTextareaToolbar">
            <jsc-button class="inputTextareaCancelBtn" csstype="CANCEL">取消</jsc-button>
            <jsc-button class="inputTextareaSaveBtn">确认</jsc-button>
        </div>
    </div>`;

    #value;
    #inputTextarea = undefined;
    #required = false;
    #jscBind = null;
    #maxlength = null;
    #closeByModal = false;
    #title = '编辑'; // 标题文案
    #cancelBtnText = undefined; // 取消按钮
    #saveBtnText = undefined; // 保存按钮

    constructor() {
        super();
        this.#init();
        this.#render();
    }

    connectedCallback() {
        this.#bindEventTextarea();
    }

    disconnectedCallback() {
    }

    attributeChangedCallback(name, oldValue, newValue) {
        switch (name) {
            case 'value': {
                if (oldValue != newValue) {
                    this.value = newValue;
                }
                break;
            }
            case 'required': {
                if (oldValue != newValue) {
                    if (null == newValue) {
                        this.#required = false;
                    } else {
                        this.#required == newValue;
                    }
                }
                break;
            }
            case 'disabled': {
                if (oldValue != newValue) {
                    if (newValue || '' == newValue) {
                        this.#inputTextarea.setAttribute('disabled', true);
                    } else {
                        this.#inputTextarea.removeAttribute('disabled');
                    }
                }
                break;
            }
            case 'jscbind': {
                if (oldValue != newValue) {
                    this.#jscBind = newValue;
                }
                break;
            }
        }
    }
    bindRefresh(bindStamp) {
        if (super.bindRefresh(bindStamp)) {
            if (null != this.bind && null != this.#jscBind) {
                this.#value = this.fetchBindValue(this.#jscBind);
                this.#inputTextarea.value = this.#value;
            }
        }
    }
    set value(val) {
        let self = this;
        let oldValue = self.#value;
        if (oldValue == val) {
            return;
        }
        self.#value = val;
        this.#inputTextarea.value = self.#value;
        this.updateBindValue(this.#jscBind, this.#value);
        this.checkValidity();
    }

    get value() {
        return this.#value;
    }

    #init() {
        let closeByModal = this.getAttribute('closebymodal');
        if (null == closeByModal) {
            this.#closeByModal = false;
        } else {
            this.#closeByModal = true;
        }
        this.#maxlength = this.getAttribute('maxlength');
        this.#jscBind = this.getAttribute('jscbind');
        if (this.getAttribute('title')) { // 标题文本赋值
            this.#title = this.getAttribute('title')
        }
        if (this.getAttribute('cancelBtnText')) { // 取消按钮文本
            this.#cancelBtnText = this.getAttribute('cancelBtnText')
        }
        if (this.getAttribute('saveBtnText')) { // 保存按钮文本
            this.#saveBtnText = this.getAttribute('saveBtnText')
        }
    }
    // 渲染组件
    #render() {
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.innerHTML = `
        <link rel='stylesheet' type='text/css' href='${JscConfig.cssUrl}'/>
        <textarea></textarea>
        `;

        this.#inputTextarea = this.shadowRoot.querySelector('textarea');

        // 接收组件标签的属性
        if (this.getAttribute('placeholder')) {
            this.#inputTextarea.setAttribute('placeholder', this.getAttribute('placeholder'));
        }

        if (this.getAttribute('readonly')) {
            this.#inputTextarea.setAttribute('readonly', true);
        }

        if (this.getAttribute('disabled')) {
            this.#inputTextarea.setAttribute('disabled', true);
        }
    }
    // 打开组件窗口
    #openEditor() {
        let self = this;
        Jsc.showDialog({
            title: self.#title,
            content: JscInputTextarea.editorBox,
            closeWhenClickedOutside: self.#closeByModal,
            width: '61.8%',
            height: '61.8%',
            beforeOpen: function (dialog) {
                let dialogContainer = dialog.fetchContainer();
                let inputTextareaEditor = dialogContainer.querySelector('.inputTextareaEditor');
                let inputTextareaCounter = dialogContainer.querySelector('.inputTextareaCounter');
                let inputTextareaCancelBtn = dialogContainer.querySelector('.inputTextareaCancelBtn');
                let inputTextareaSaveBtn = dialogContainer.querySelector('.inputTextareaSaveBtn');

                inputTextareaEditor.placeholder = self.#inputTextarea.placeholder;
                inputTextareaEditor.value = self.#inputTextarea.value;
                if (self.#maxlength) {
                    inputTextareaCounter.style.display = 'block';
                    inputTextareaEditor.maxlength = self.#inputTextarea.maxlength;
                    inputTextareaCounter.innerText = inputTextareaEditor.value.length + '/' + self.#maxlength;
                    inputTextareaEditor.addEventListener('input', function (e) {
                        let length = inputTextareaEditor.value.length
                        inputTextareaCounter.innerText = length > self.#maxlength ? self.#maxlength + '/' + self.#maxlength : length + '/' + self.#maxlength;
                    });
                } else {
                    inputTextareaCounter.style.display = 'none';
                }

                inputTextareaCancelBtn.addEventListener('click', function (e) {
                    dialog.close();
                });

                inputTextareaSaveBtn.addEventListener('click', function (e) {
                    self.#inputTextarea.value = inputTextareaEditor.value;
                    self.value = inputTextareaEditor.value;
                    dialog.close();
                });
            },
            afterOpen: function (dialog) {
                let dialogContainer = dialog.fetchContainer();
                let inputTextareaEditor = dialogContainer.querySelector('.inputTextareaEditor');
                inputTextareaEditor.focus();
            }
        });
    }
    // 事件绑定
    #bindEventTextarea() {
        let self = this;
        // 打开事件
        self.#inputTextarea.addEventListener('click', function (e) {
            self.#openEditor()
        });
    }

    checkValidity() {
        let errMsg = '';
        if (this.#required && (undefined == this.#value || null == this.#value || '' == this.#value)) {
            errMsg = '该字段不能为空';
        }

        this.#inputTextarea.setCustomValidity(errMsg);
        this.#inputTextarea.reportValidity();

        if ('' === errMsg) {
            return true;
        } else {
            return false;
        }
    }
}

if (!customElements.get('jsc-input-textarea')) {
    window.customElements.define("jsc-input-textarea", JscInputTextarea);
}